package cn.flightcloud.auth.config.spring.security.provider;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

import cn.flightcloud.auth.config.spring.security.SecurityUser;

/**
 * 简单的身份认证provider
 * 
 * @author chenjj
 *
 */
public class SimpleAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

	private PasswordEncoder passwordEncoder;

	private UserDetailsService userDetailsService;

	public SimpleAuthenticationProvider(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	/**
	 * 额外的身份认证检查
	 */
	@Override
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
		// 密码校验
		if (passwordEncoder != null) {
			String password = (String) authentication.getCredentials();
			if (!passwordEncoder.matches(password, userDetails.getPassword())) {
				throw new BadCredentialsException("密码验证失败");
			}
		}
	}

	/**
	 * 检索UserDetails
	 */
	@Override
	protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		return userDetailsService.loadUserByUsername(username);
	}

	/**
	 * 身份认证成功后执行
	 */
	@Override
	protected Authentication createSuccessAuthentication(Object principal, Authentication authentication,
			UserDetails user) {
		// 身份认证通过后，获取用户的权限
		SecurityUser securityUser = (SecurityUser) user;
		securityUser.setAuthorities(securityUser.getAuthorities());

		return super.createSuccessAuthentication(principal, authentication, user);
	}
}
